package com.linchaoen.elema.service.impl;

import com.linchaoen.elema.mapper.UserMapper;
import com.linchaoen.elema.model.entity.User;
import com.linchaoen.elema.service.UserService;
import com.linchaoen.elema.utils.CommonUtil;
import com.linchaoen.elema.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int register(Map<String, String> userInfo) {
        User user = parseToUser(userInfo);
        if (user != null) {
            return userMapper.register(user);

        } else {
            return -1;
        }
    }

    @Override
    public String findByPhoneAndPwd(String phone, String pwd) {
        pwd = CommonUtil.MD5(pwd);
        User user = userMapper.findByPhoneAndPwd(phone, pwd);
        if (user == null) {
            return null;
        } else {
            String token = JWTUtil.geneJsonWebToken(user);
            return token;
        }
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public int updateUserInfo(Integer uid, String name, String signature) {
        return userMapper.updateUserInfo(uid, name, signature);
    }

    @Override
    public int resetPwd(Integer uid, String oldPwd, String newPwd) {
        newPwd = CommonUtil.MD5(newPwd);
        oldPwd = CommonUtil.MD5(oldPwd);
        return userMapper.resetPwd(uid,oldPwd,newPwd);
    }

    private User parseToUser(Map<String, String> userInfo) {
        if (userInfo.containsKey("name") && userInfo.containsKey("phone") && userInfo.containsKey("pwd")) {
            String name = userInfo.get("name");
            String phone = userInfo.get("phone");
            String pwd = userInfo.get("pwd");
            User user = new User();
            user.setName(name);
            user.setPhone(phone);
            //MD5加密密码
            pwd = CommonUtil.MD5(pwd);
            user.setPwd(pwd);
            user.setHeadImg(getRandomImg());
            return user;
        } else {
            return null;
        }
    }

    //获取随机头像
    private String getRandomImg() {
        Random random = new Random();
        int i = random.nextInt(headImg.length);
        return headImg[i];
    }

    //随机头像数据
    private static final String[] headImg = {
            "http://8.134.193.67/images/head1.jpg",
            "http://8.134.193.67/images/head2.jpg",
            "http://8.134.193.67/images/head3.jpg",
    };
}
